package com.splic.common.utils.security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

public class AESUtils {
    public static void main(String[] args) throws Exception {
//        try {
//            // 获取AES密钥生成器
//            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
//
//            // 初始化密钥生成器，指定密钥长度为256位（需要Java Cryptography Extension (JCE) 无限强度司法管辖权策略文件）
//            keyGenerator.init(128);
//
//            // 生成密钥
//            SecretKey secretKey = keyGenerator.generateKey();
//
//            // 输出密钥信息
//            System.out.println("AES Key generated: " + HexUtil.encodeHexStr(secretKey.getEncoded()));
//            // 注意：通常你不会直接打印或输出密钥的原始字节，这里仅作为示例
//
//            // 如果需要将密钥转换为字符串以便传输或存储，可以使用Base64编码
//            // 例如，使用java.util.Base64进行编码
//            String encodedKey = java.util.Base64.getEncoder().encodeToString(secretKey.getEncoded());
//            System.out.println("Base64 encoded AES Key: " + encodedKey);
//
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        System.out.println(AESUtils.decrypt("Cnbpk3lkByQyXFQjU736GoxfZlO6kyQnbsVtgOAcnbCzKsUXb6odTI4LoA0jPGfmmwdLvnt0ACBdo8yFHzgqbkLxspNgJ5331qhk2Q9P1njuSmGCy7T3iwvxIOP2OtOoVMI0VhKFC6EUR3Jrdh6ZuAoObR+ZPtN2EDZIn4NTW8pyzFeysXF0bPLtX1VOE82s46Y71PiyTBAZcpglmy2pYatu8lpRtBy/0oYszayU9tHJpwqs3lIieGq7Al6jE8tNAJJhxP0EagNqqmFjfwxolv/C21kzYj8UqzWP442/QrJmG7N+jWLPYoWsBquhAnLACLm9Gn9OOpaoMiUJTjjWZyhffIU3B99DFGqeP2NLi2GomSCCq+rSpn5nK3mxiwOt2sM9q7WcPL8fmjG91nTH1tcOoIvKwafslgK+PUWhNKzZwRDJ3u/85RaklFu2rexXhFC2IJzZfO+iUhwnOB5qNQ==", "j+xee5ObfmcqbuvUU7cTaejdPEvlzDzWhP9nlJSmvNg="));;
//        System.out.println(AESUtils.encrypt("{\"androidId\":\"031d77710b2884be\",\"appPackage\":\"ej.easyjoy.easyrecorder.cn\",\"baseOS\":\"Android\",\"branchOS\":\"HONOR\",\"channelId\":\"default\",\"deviceIdentify\":\"DE2024051423120160\",\"gaid\":\"\",\"imei\":\"\",\"mac\":\"\",\"oaid\":\"ce368007-c781-48b9-a439-934795460ba1\",\"packageKey\":\"1444A54DA77B67E175B242C95B3FD42B\",\"userIdentify\":\"\",\"version\":\"5.9.547.Test\"}", "pRvxtOnSZepDn1kTNXdxIw=="));;
        System.out.println(AESUtils.decrypt("Lg4nFyY6ldb2YZ9Jh3zlIOuuPKtWRDi1jD6fmWvYe/6PW+tb1vMG8MfLKEJXr6AmS7TApfMcqAGwt+o+MJnrUaHs/Ijpl7ISK12+n/TCbKt/PvmwJLxr9fhW7r4C5BJC5+0pPQcRnsbp3sTMkpt9D7OpqfVRzhsRfAEAAR38QbeLl/eTENeruYJHkfvS0hR+ILnx/x5n8XOTgoRCTPPVfP9a+UYFLoI+h/PwFkGBikfxroeydj9ahApp0Mf6cb2WiWqTvo5hOVszUITV5mFCMri4eFSNYz5eKalbk6b6hjRcd/npE1nAySTuXBemmB3XORnzpIENnGP8kDIe5ITq5iupjyhCW6+mNZjHQlxsMO6tlOr2L9gyheAh8+KZQ3/21fdPFEFC2uYgrOzIMrjA7yY+ndPsBpqhJU9LN/0BYZHjpEsSozuQqstpraQxwLzBn5AjSj1glxEzzCkqosCr6g==", "pRvxtOnSZepDn1kTNXdxIw=="));;
    }


    public static String encrypt(String plainText, String keyString) throws Exception {

        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(keyString), "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedText, String keyString) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(keyString), "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    private static byte[] generateAesKey(String keyString) throws NoSuchAlgorithmException {
        // 使用SHA-256哈希并截取前16字节生成密钥
        MessageDigest md = MessageDigest.getInstance("SHA-128");
        byte[] key = md.digest(keyString.getBytes(StandardCharsets.UTF_8));
        return Arrays.copyOf(key, 16);
    }
}
